<template>
  <div class="performance-monitor">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>性能监控面板</span>
        <div style="float: right">
          <el-button
            type="primary"
            size="small"
            @click="refreshData"
            icon="el-icon-refresh"
            :loading="loading"
            >刷新数据</el-button
          >
          <el-button
            type="danger"
            size="small"
            @click="resetPerformanceMetrics"
            style="margin-left: 10px"
            >重置统计</el-button
          >
        </div>
      </div>

      <div v-if="performanceData" class="performance-content">
        <!-- 文件处理统计 -->
        <el-row :gutter="20" class="stats-row">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ performanceData.filesProcessed }}</div>
                <div class="stat-label">处理文件数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ formatBytes(performanceData.processedBytes) }}</div>
                <div class="stat-label">处理字节数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ performanceData.processedLines.toLocaleString() }}</div>
                <div class="stat-label">处理行数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ performanceData.slowSqlCount }}</div>
                <div class="stat-label">慢SQL数量</div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 性能指标 -->
        <el-row :gutter="20" class="stats-row">
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ formatThroughput(performanceData.throughput) }}</div>
                <div class="stat-label">平均吞吐量</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ formatLinesPerSecond(performanceData.linesPerSecond) }}</div>
                <div class="stat-label">处理速度(行/秒)</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ performanceData.regexMatchRate.toFixed(2) }}%</div>
                <div class="stat-label">正则匹配成功率</div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 缓存统计 -->
        <el-row :gutter="20" class="stats-row">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ performanceData.maxCacheSize }}</div>
                <div class="stat-label">最大缓存大小</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ performanceData.cacheCleanups }}</div>
                <div class="stat-label">缓存清理次数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ performanceData.cacheEvictions }}</div>
                <div class="stat-label">缓存驱逐数量</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ performanceData.errors }}</div>
                <div class="stat-label">错误数量</div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 正则匹配统计 -->
        <el-row :gutter="20" class="stats-row">
          <el-col :span="12">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ performanceData.regexAttempts.toLocaleString() }}</div>
                <div class="stat-label">正则匹配尝试次数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ performanceData.regexMatches.toLocaleString() }}</div>
                <div class="stat-label">正则匹配成功次数</div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 处理时间统计 -->
        <el-row :gutter="20" class="stats-row">
          <el-col :span="12">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ formatTime(performanceData.processingTime) }}</div>
                <div class="stat-label">总处理时间</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ formatAverageTime(performanceData.processingTime, performanceData.filesProcessed) }}</div>
                <div class="stat-label">平均文件处理时间</div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 性能建议 -->
        <el-card class="suggestions-card">
          <div slot="header">
            <span>性能优化建议</span>
          </div>
          <div class="suggestions-content">
            <div v-if="performanceData.throughput < 1024 * 1024" class="suggestion-item">
              <i class="el-icon-warning" style="color: #E6A23C;"></i>
              <span>吞吐量较低，建议增加批处理大小或使用更多线程</span>
            </div>
            <div v-if="performanceData.linesPerSecond < 1000" class="suggestion-item">
              <i class="el-icon-warning" style="color: #E6A23C;"></i>
              <span>行处理速度较慢，建议优化正则表达式或减少字符串操作</span>
            </div>
            <div v-if="performanceData.regexMatchRate < 50" class="suggestion-item">
              <i class="el-icon-warning" style="color: #E6A23C;"></i>
              <span>正则匹配效率低，建议优化正则表达式或添加预过滤条件</span>
            </div>
            <div v-if="performanceData.maxCacheSize > 5000" class="suggestion-item">
              <i class="el-icon-warning" style="color: #E6A23C;"></i>
              <span>缓存使用较多，建议增加缓存清理频率或优化SQL匹配逻辑</span>
            </div>
            <div v-if="performanceData.errors > 0" class="suggestion-item">
              <i class="el-icon-warning" style="color: #E6A23C;"></i>
              <span>存在错误，建议检查日志格式一致性或增强错误处理机制</span>
            </div>
            <div v-if="!hasWarnings" class="suggestion-item">
              <i class="el-icon-success" style="color: #67C23A;"></i>
              <span>系统性能良好，各项指标都在正常范围内</span>
            </div>
          </div>
        </el-card>
      </div>

      <div v-else class="no-data">
        <el-empty description="暂无性能数据，请先进行日志分析"></el-empty>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "PerformanceMonitor",
  data() {
    return {
      performanceData: null,
      loading: false,
      apiBaseUrl: "http://localhost:8080/api/template",
    };
  },
  computed: {
    hasWarnings() {
      if (!this.performanceData) return false;
      return (
        this.performanceData.throughput < 1024 * 1024 ||
        this.performanceData.linesPerSecond < 1000 ||
        this.performanceData.regexMatchRate < 50 ||
        this.performanceData.maxCacheSize > 5000 ||
        this.performanceData.errors > 0
      );
    },
  },
  created() {
    this.loadPerformanceData();
  },
  methods: {
    async loadPerformanceData() {
      this.loading = true;
      try {
        const response = await axios.get(`${this.apiBaseUrl}/performance`);
        if (response.data.success) {
          this.performanceData = response.data.data;
        } else {
          this.$message.error(response.data.message || "获取性能数据失败");
        }
      } catch (error) {
        this.$message.error("获取性能数据失败: " + error.message);
      } finally {
        this.loading = false;
      }
    },
    async refreshData() {
      await this.loadPerformanceData();
      this.$message.success("性能数据已刷新");
    },
    async resetPerformanceMetrics() {
      this.$confirm('确定要重置所有性能统计数据吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          this.loading = true;
          try {
            const response = await axios.post(`${this.apiBaseUrl}/performance/reset`);
            if (response.data.success) {
              this.$message.success('性能统计已重置');
              await this.loadPerformanceData();
            } else {
              this.$message.error(response.data.message || '重置失败');
            }
          } catch (error) {
            this.$message.error('重置失败: ' + error.message);
          } finally {
            this.loading = false;
          }
        })
        .catch(() => {});
    },
    formatBytes(bytes) {
      if (bytes === 0) return "0 B";
      const k = 1024;
      const sizes = ["B", "KB", "MB", "GB"];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
    },
    formatThroughput(throughput) {
      if (throughput === 0) return "0 KB/s";
      const k = 1024;
      const sizes = ["B/s", "KB/s", "MB/s", "GB/s"];
      const i = Math.floor(Math.log(throughput) / Math.log(k));
      return parseFloat((throughput / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
    },
    formatLinesPerSecond(lps) {
      if (lps === 0) return "0 行/秒";
      if (lps >= 1000) {
        return (lps / 1000).toFixed(2) + "K 行/秒";
      }
      return lps.toFixed(2) + " 行/秒";
    },
    formatTime(milliseconds) {
      if (milliseconds === 0) return "0ms";
      if (milliseconds < 1000) {
        return milliseconds + "ms";
      }
      const seconds = Math.floor(milliseconds / 1000);
      const remainingMs = milliseconds % 1000;
      return seconds + "s " + remainingMs + "ms";
    },
    formatAverageTime(totalTime, fileCount) {
      if (fileCount === 0) return "0ms";
      const avgTime = totalTime / fileCount;
      return this.formatTime(avgTime);
    },
  },
};
</script>

<style scoped>
.performance-monitor {
  width: 100%;
  margin: 1% auto;
}

.performance-content {
  margin-top: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.stat-item {
  padding: 20px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.suggestions-card {
  margin-top: 20px;
}

.suggestions-content {
  padding: 10px 0;
}

.suggestion-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 8px 0;
}

.suggestion-item i {
  margin-right: 8px;
  font-size: 16px;
}

.suggestion-item span {
  font-size: 14px;
  color: #606266;
}

.no-data {
  text-align: center;
  padding: 40px 0;
}
</style> 